/*-+-*****************************************************************************
 Copyright (C) 2009-2012 Oceanside Software Corporation (R)
 Dallas, Texas

 Author       : Jason T. Brower
 Purpose      : This file is part of a point-of-sale software package
                originally written for Table-Service Restaurants.
              
 Date         : July 8th of 2012
              
 History      : The application that this software file belongs to was 
                written over a 3-Year period.  The first version was written
                in C# .Net 3.5 using Windows Forms.  Being new to .Net at
                the time, I soon learned of Windows Presentation Foundation,
                liked the graphics capabilities and databinding so I
                migrated to WPF.  When the .Net 4.0 framework was released
                the application was migrated from 3.5 to 4.0. Now today,
                .Net 4.5 RC is out and I was already in process of migrating
                before I made this public.
                
Excuse Me     : Please excuse the coding style, it is not representative of
                my typical work.  During the three years I was under a very
                tight budget, constantly running out of funding and was 
                working 18 hour days hyped up on 5-Hour Energy.  The 
                design is not textbook.  It is monolythic because of
                previous issues I will not get into.  There are few comments
                in the code and the ones that are there may be incorrect.
                
What it is not: This is not the exact version that I took through PA-DSS 2.0
                nor is it the exact version running at my customer sites.
                I removed some details for security purposes including some
                encryption algorithms.  The reporting was removed because
                I was including a third party library that cannot be 
                published with this Open Source.
                
What it is    : This application has been running at high volume restaraunts
                for over a year.  It never freezes, crashes or does anything
                unexpected.  So long as it is built, installed and configured
                correctly, it is a strong system that we can all enhance.

Contact       : Please note that I can no longer work for free.  However, you
                can reach me at information@oceansidesw.com.                                                      

*********************************************************************************/
using System.Collections;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Data.Objects;
using System.Data.Objects.DataClasses;
using System.Linq;
using System.Windows;
using System.Windows.Controls;
using System;
#if _LOCALDB
  using Oceanside.LocalDB;
#else
using Oceanside.RemoteDB;
#endif
namespace Oceanside
{
    /// <summary>
    /// 
    /// </summary>
    public partial class PageMapKioskProdGroupToPrinterImp : PageImpBaseClass
    {
        ListView listviewAvailablePrinters;
        ListView listviewUnmatchedGroups;
        ListView listviewPairs;
        ComboBox comboBoxName;

        Button buttonDelete;
        Button buttonNew;
        /// <summary>
        /// Constructor
        /// </summary>
        public PageMapKioskProdGroupToPrinterImp(
            UIElementCollection stackpanContrlChild,
            ListView listviewAvailablePrinters,
            ListView listviewUnmatchedGroups,
            ListView listviewPairs,
            ComboBox comboBoxName,
            Button buttonDelete,
            Button buttonNew)
        {
            this.buttonDelete = buttonDelete;
            this.buttonNew = buttonNew;

            this.ButtonNumber = "19";
            this.ButtonLabelText = "  KIOSK Printer Group Map"; ///Extra spaces are for alignment

            mNewGroupIsDisabled = true;
            mDeleteGroupIsDisabled = true;
            mDeleteEntityIsDisabled = true;
            mNewEntityIsDisabled = true;

            this.listviewAvailablePrinters = listviewAvailablePrinters;
            this.listviewUnmatchedGroups = listviewUnmatchedGroups;
            this.listviewPairs = listviewPairs;
            this.comboBoxName = comboBoxName;

            buttonDelete.Click += new RoutedEventHandler(buttonDelete_Click);
            buttonNew.Click += new RoutedEventHandler(buttonJoin_Click);

            ///Register the controls and lock the form.
            RegisterUiElementsList(stackpanContrlChild);
            RegisterListview(listviewAvailablePrinters);
            RegisterListview(listviewUnmatchedGroups);
            RegisterListview(listviewPairs);

            ///Add the combo boxes.
            ListofComboboxes.Add(comboBoxName);

            listviewUnmatchedGroups.SelectionChanged += new SelectionChangedEventHandler(listview_SelectionChanged_NOTHROW);
            listviewAvailablePrinters.SelectionChanged += new SelectionChangedEventHandler(listview_SelectionChanged_NOTHROW);
            listviewPairs.SelectionChanged += new SelectionChangedEventHandler(listview_SelectionChanged_NOTHROW);

            ///If the selection changes lock the form down.
            comboBoxName.SelectionChanged += new SelectionChangedEventHandler(comboBoxName_SelectionChanged_NOTHROW);

            mListOfControlsToHideInNonEditMode.Add(buttonDelete);
            mListOfControlsToHideInNonEditMode.Add(buttonNew);

            mEntityAddDeleteLoggingEnabled = true;

        }

        /// <summary>
        /// 
        /// </summary>
        /// <returns></returns>
        override public List<EntityObject> GetEntityObjectSet()
        {
            try
            {
                var q = from MAP_KIOSK_PRODUCT_GROUP_AND_PRINTER_GROUP
                        in Context.MAP_KIOSK_PRODUCT_GROUP_AND_PRINTER_GROUPS
                        select MAP_KIOSK_PRODUCT_GROUP_AND_PRINTER_GROUP;

                if (q.Any())
                {
                    return new List<EntityObject>(q.ToList());
                }
            }
            catch (Exception e)
            {
                Logging.LogException(e);
            }
            return null;
        }


        /// <summary>
        /// 
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        void comboBoxName_SelectionChanged_NOTHROW(object sender, SelectionChangedEventArgs e)
        {
            try
            {
                UpdateListViews();
            }
            catch (System.Exception exc)
            {
                Constants.ErrorDispatcher.Notify(Error.EType.E_PLACEHOLDER, exc);
            }
        }

        private void UpdateListViews()
        {
            try
            {
                KIOSK selectedKiosk = comboBoxName.SelectedItem as KIOSK;
                if (selectedKiosk != null)
                {
                    ///Load the existing pairs for this KIOSK, then assign the existing pairs to the 
                    ///appropriate listview.
                    selectedKiosk.MAP_KIOSK_PRODUCT_GROUP_AND_PRINTER_GROUPS.Load();
                    var q = from M in selectedKiosk.MAP_KIOSK_PRODUCT_GROUP_AND_PRINTER_GROUPS select M;
                    if (q.Any())
                    {
                        listviewPairs.ItemsSource = q.ToList();
                    }
                    else
                    {
                        listviewPairs.ItemsSource = null;
                    }

                    ///The complex query below will find all product groups for the selected KIOSK that are
                    ///not currently joined with a printer.
                    var q1 = from PG in Context.PRODUCT_GROUPS where PG.IsDeleted == false
                             let usedIds = from MAP in Context.MAP_KIOSK_PRODUCT_GROUP_AND_PRINTER_GROUPS
                                               .Include("KIOSK").Include("PRODUCT_GROUP")
                                           where MAP.KIOSK.Id == selectedKiosk.Id
                                           select MAP.PRODUCT_GROUP.Id
                             where !usedIds.Contains(PG.Id)
                             select PG;

                    if (q1.Any())
                    {
                        listviewUnmatchedGroups.ItemsSource = q1.ToList();
                    }
                    else
                    {
                        listviewUnmatchedGroups.ItemsSource = null;
                    }

                    ///Now we must find the list of product group printers that are available to chose from.
                    ///This is easy.
                    var q2 = from PG in Context.PRINTER_GROUPS where PG.IsDeleted == false select PG;
                    if (q2.Any())
                    {
                        listviewAvailablePrinters.ItemsSource = q2.ToList();
                    }
                    else
                    {
                        listviewAvailablePrinters.ItemsSource = null;
                    }
                }
            }
            catch (System.Exception exc)
            {
                Constants.ErrorDispatcher.Notify(Error.EType.E_PLACEHOLDER, exc);
            }
        }
        /// <summary>
        /// 
        /// </summary>
        public override void ResetFocus()
        {
            base.ResetFocus();
            buttonDelete.IsEnabled = false;
            buttonNew.IsEnabled = false;
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        void listview_SelectionChanged_NOTHROW(object sender, SelectionChangedEventArgs e)
        {
            try
            {
                ListView lv = sender as ListView;
                if (lv == listviewPairs)
                {
                    listviewUnmatchedGroups.SelectedItem = null;
                    listviewAvailablePrinters.SelectedItem = null;
                    buttonNew.IsEnabled = false;
                    buttonDelete.IsEnabled = true;
                }
                else
                {
                    listviewPairs.SelectedItem = null;
                    buttonNew.IsEnabled = true;
                    buttonDelete.IsEnabled = false;
                }
            }
            catch (System.Exception exc)
            {
                Constants.ErrorDispatcher.Notify(Error.EType.E_PAGEPRODUCTGROUPPRINTER_LV_SELECTION_CHANGED, exc);
            }
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void buttonJoin_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                int count = listviewUnmatchedGroups.SelectedItems.Count;
                KIOSK kiosk = comboBoxName.SelectedItem as KIOSK;
                if (count != 0 && listviewAvailablePrinters.SelectedItems.Count != 0 && kiosk != null)
                {
                    foreach (PRODUCT_GROUP pg in listviewUnmatchedGroups.SelectedItems)
                    {
                        MAP_KIOSK_PRODUCT_GROUP_AND_PRINTER_GROUP newDbObject = new MAP_KIOSK_PRODUCT_GROUP_AND_PRINTER_GROUP();
                        newDbObject.PRODUCT_GROUP = pg;
                        newDbObject.PRINTER_GROUP = listviewAvailablePrinters.SelectedItem as PRINTER_GROUP;
                        newDbObject.KIOSK = kiosk;
                    }
                    Context.SaveChanges();
                    UpdateListViews();

                    listviewUnmatchedGroups.SelectedItem = null;
                    listviewAvailablePrinters.SelectedItem = null;
                    listviewPairs.SelectedItem = null;

                    buttonNew.IsEnabled = false;
                    buttonDelete.IsEnabled = false;
                }
            }
            catch (Exception ex)
            {
                Logging.LogException(ex);
            }
        }

        /// <summary>
        /// 
        /// </summary>
        /// <returns></returns>
        public override EntityObject GetSelectedEntityObject()
        {
            KIOSK selected = comboBoxName.SelectedItem as KIOSK;
            return selected;
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="source"></param>
        public override void UpdateUsersEntitySource()
        {
            try
            {
                var q = from K in Context.KIOSKS where K.IsDeleted == false select K;
                if (q.Any())
                {
                    comboBoxName.ItemsSource = q.ToList();
                }
                else
                {
                    comboBoxName.ItemsSource = null;
                }
                UpdateListViews();
            }
            catch (Exception e)
            {
                Logging.LogException(e);
            }
        }

        /// <summary>
        /// 
        /// </summary>
        /// <returns></returns>
        public override ComboBox GetEntityComboBox()
        {
            return comboBoxName;
        }


        /// <summary>
        /// 
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void buttonDelete_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                IList joinList = listviewPairs.SelectedItems;
                foreach (MAP_KIOSK_PRODUCT_GROUP_AND_PRINTER_GROUP selected in joinList)
                {
                    Context.MAP_KIOSK_PRODUCT_GROUP_AND_PRINTER_GROUPS.DeleteObject(selected);
                }

                Context.SaveChanges();
                KIOSK kiosk = comboBoxName.SelectedItem as KIOSK;

                UpdateListViews();
                
                listviewUnmatchedGroups.SelectedItem = null;
                listviewAvailablePrinters.SelectedItem = null;
                listviewPairs.SelectedItem = null;

                buttonNew.IsEnabled = false;
                buttonDelete.IsEnabled = false;
            }
            catch (Exception ex)
            {
                Logging.LogException(ex);
            }
        }
    }
}
